import { useId, useState, type ChangeEvent } from "react";
import PlusIcon from "@/assets/icons/plus.svg?jsx";
import useFetch from "@/lib/hooks/useFetch";
import { uploadDeviceImage } from "@/lib/api/device";
import { useAtomValue } from "jotai";
import { tokenAtom } from "@/store/user";

type UploadProps = {
  value?: string;
  onChange?: (path: string) => void;
};

export default function Upload(props: UploadProps) {
  const { value, onChange } = props;
  const id = useId();
  const [file, setFile] = useState<File>();
  const token = useAtomValue(tokenAtom);

  const { isLoading, refetch: upload } = useFetch({
    fetchFn: (file: File) =>
      uploadDeviceImage(file, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.fileName;
      }),
    onSuccess(path) {
      onChange?.(path);
      console.log({ path });
    },
  });

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    console.log({ file });
    setFile(file);
    file && upload(file);
  }

  return (
    <div>
      <label
        htmlFor={id}
        className="flex aspect-square h-36 cursor-pointer flex-col items-center justify-center gap-y-8 rounded border border-dashed border-zinc-500 transition-all hover:border-sky-500 hover:text-sky-500"
      >
        {!!file ? (
          <span className="text-center text-sm">{file.name}</span>
        ) : (
          <>
            <PlusIcon />
            <span>上传照片</span>
          </>
        )}
      </label>
      <input
        id={id}
        accept="image/jpg,image/png"
        type="file"
        className="!hidden"
        onChange={handleChange}
      />
    </div>
  );
}
